package XZK010205.service;

import java.util.Random;

import XZK010205.bean.Express;
import XZK010205.dao.ExpressDao;

/**
 * 快递E站-快递存储操作逻辑类
 *
 * @author bing.z 2021/5/31 20:42
 **/
public class ExpressService {
    /**
     * 快递存储操作类
     */
    private ExpressDao expressDao = new ExpressDao();
    /**
     * 随机数类
     */
    private Random random = new Random();

    /**
     * 添加快递
     *
     * @param express
     * @return 包含取件码的快递对象
     */
    public Express insert(Express express) {
        // 0. 获取所有快递信息
        Express[][] allExpress = getAll();
        // 快递柜已满
        if (allExpress != null && getSize() == allExpress.length * allExpress[0].length) {
            return null;
        }
        // 1.获取柜子位置
        int x = -1, y = -1;
        do {
            x = random.nextInt(10);
            y = random.nextInt(10);
        } while (allExpress[x][y] != null);
        // 2.获取取件码(6位)
        // 100000 - 999999
        int code = -1;
        while (true) {
            // 取件码唯一性
            boolean same = false;
            code = random.nextInt(899999) + 100000;
            m:
            for (Express[] expressesRow : allExpress) {
                for (Express es : expressesRow) {
                    if (es != null && es.getCode() == code) {
                        same = true;
                        break m;
                    }
                }
            }
            if (!same) {
                break;
            }
        }
        express.setCode(code);
        // 插入数据
        expressDao.insert(x, y, express);
        return express;
    }

    /**
     * 根据快递单号删除快递
     *
     * @param number 快递单号
     * @return
     */
    public boolean delete(String number) {
        return expressDao.delete(number);
    }

    /**
     * 根据传入对象的快递单号，更新快递信息
     *
     * @param express
     */
    public boolean update(Express express) {
        return expressDao.update(express);
    }

    /**
     * 获取所有快递信息
     *
     * @return
     */
    public Express[][] getAll() {
        return expressDao.getAll();
    }

    /**
     * 获取已存储快递数量
     *
     * @return
     */
    public int getSize() {
        return expressDao.getSize();
    }

    /**
     * 根据取件码取件
     *
     * @param code
     */
    public Express takeByCode(int code) {
        Express express = expressDao.getByCode(code);
        if (express != null) {
            expressDao.delete(express.getNumber());
        }
        return express;
    }

    /**
     * 根据单号获取快递对象
     *
     * @param number
     * @return
     */
    public Express getByNumber(String number) {
        return expressDao.getByNumber(number);
    }
}
